package com.zlz.m3u8download.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zlz.m3u8download.bean.entity.SeaPlayDataEntity;
import com.zlz.m3u8download.mapper.SeaPlayDataMapper;
import com.zlz.m3u8download.service.DownloadService;
import com.zlz.m3u8download.service.SeaCmsService;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SeaCmsServiceImpl implements SeaCmsService {

    private final SeaPlayDataMapper seaPlayDataMapper;


    public SeaCmsServiceImpl(SeaPlayDataMapper seaPlayDataMapper) {
        this.seaPlayDataMapper = seaPlayDataMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> getSourceList(Long vid, String sourceId) {
        // 查询需要缓存的任务信息
        SeaPlayDataEntity seaPlayDataEntity = seaPlayDataMapper.selectOne(Wrappers.<SeaPlayDataEntity>lambdaQuery()
                .eq(SeaPlayDataEntity::getVid, vid));
        if (seaPlayDataEntity == null || StringUtils.isEmpty(seaPlayDataEntity.getBody())) {
            return Collections.emptyList();
        }

        String infos = seaPlayDataEntity.getBody();
        String[] sourceList = infos.split("\\$\\$\\$");
        if (sourceList.length == 0) {
            return Collections.emptyList();
        }

        // 名称：数据集合
        Map<String, String> sources = Arrays.stream(sourceList).collect(Collectors.toMap(s -> s.split("\\$\\$")[0],
                s -> s.split("\\$\\$")[1]));

        if (sources.containsKey("local")) {
            return Collections.emptyList();
        }
        String taskSourcesStr = null;
        if (sourceId != null) {
            if (sources.containsKey(sourceId)) {
                taskSourcesStr = sources.get(sourceId);
            } else {
                return Collections.emptyList();
            }
        } else {
            taskSourcesStr = sources.get(sourceList[0].substring(0, sourceList[0].indexOf("$")));
        }
        if (taskSourcesStr == null) {
            return Collections.emptyList();
        }

        // 开始解析
        String[] lists = taskSourcesStr.split("#");
        List<String> news = new ArrayList<>();
        for (String source : lists) {
            String[] $s = source.split("\\$");
            if ($s.length != 3) {
                return Collections.emptyList();
            }
            String name = $s[0];
        }

        String newSource = "本地$$" + String.join("#", news);

        // 解析并创建任务
        seaPlayDataEntity.setBody(seaPlayDataEntity.getBody() + "$$$" + newSource);
        seaPlayDataMapper.update(seaPlayDataEntity, Wrappers.<SeaPlayDataEntity>lambdaUpdate()
                .eq(SeaPlayDataEntity::getVid, vid)
        );
        return news;
    }
}
